package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.cache.J2CacheUtils;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.utils.CharUtil;
import com.platform.utils.DateUtils;
import com.platform.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * API优惠券管理
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * @date 2017-03-23 15:31
 */
@Api(tags = "优惠券")
@RestController
@RequestMapping("/api/coupon")
public class ApiCouponController extends ApiBaseAction {
    private static final Logger logger = LoggerFactory.getLogger(ApiCouponController.class);

    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiProductService apiProductService;
    @Autowired
    private ApiCartService apiCartService;
    @Autowired
    private ApiCouponGoodsService apiCouponGoodsService;
    /**
     * 获取优惠券列表
     */
    @ApiOperation(value = "获取优惠券列表")
    @PostMapping("/list")
    public Object list(@LoginUser UserVo loginUser) {
        logger.info("【请求开始】我的->优惠券,请求参数:{}",loginUser);

        Map param = new HashMap();
        param.put("user_id", loginUser.getUserId());
        List<CouponVo> couponVoList = apiCouponService.queryUserCoupons(param);
        logger.info("【请求结束】我的->优惠券,响应结果:{}",couponVoList);
        return toResponsSuccess(couponVoList);
    }

    /*
    * 用户不管登没登录都可以看
    * */
    @IgnoreAuth
    @ApiOperation(value = "通过优惠券类型获取优惠券")
    @PostMapping("/getCouponByType")
    public Object getCouponByType() {
        List<CouponVo> couponVos = apiCouponService.queryList(null);
        return toResponsSuccess(couponVos);
    }

    /**
     * 首页优惠券
     */



    /**
     * 根据商品获取可用优惠券列表
     */
    @ApiOperation(value = "根据商品获取可用优惠券列表")
    @PostMapping("/listByGoods")
    public Object listByGoods(@RequestParam(defaultValue = "cart") String type, @LoginUser UserVo loginUser) {
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        if (type.equals("cart")) {
            Map param = new HashMap();
            param.put("user_id", loginUser.getUserId());
            List<CartVo> cartList = apiCartService.queryList(param);
            //非特价
            BigDecimal notSpecialOfferPrice = new BigDecimal(0);
            //获取购物车统计信息
            for (CartVo cartItem : cartList) {
                if (null != cartItem.getChecked() && 1 == cartItem.getChecked() && cartItem.getIsSpecialOffer()==0) {
                    goodsTotalPrice = goodsTotalPrice.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
                }
            }
        }
//        else { // 是直接购买的
//            BuyGoodsVo goodsVo = (BuyGoodsVo) J2CacheUtils.get(J2CacheUtils.SHOP_CACHE_NAME, "goods" + loginUser.getUserId() + "");
//            ProductVo productInfo = apiProductService.queryObject(goodsVo.getProductId());
//            //商品总价
//            goodsTotalPrice = productInfo.getRetail_price().multiply(new BigDecimal(goodsVo.getNumber()));
//        }

        // 获取可用优惠券
        Map param = new HashMap();
        param.put("user_id", loginUser.getUserId());
        param.put("coupon_status", 1);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(param);
        List<CouponVo> useCoupons = new ArrayList<>();
        List<CouponVo> notUseCoupons = new ArrayList<>();
        for (CouponVo couponVo : couponVos) {
            //couponTypeId=4每满100-20
            if (4==couponVo.getCouponTypeId() && goodsTotalPrice.compareTo(new BigDecimal(100))==-1){
                couponVo.setEnabled(0);
                notUseCoupons.add(couponVo);
                continue;
            }
            if (4==couponVo.getCouponTypeId() && goodsTotalPrice.compareTo(new BigDecimal(100))==1){

                couponVo.setEnabled(1);
                useCoupons.add(couponVo);
                continue;
            }

            if (4!=couponVo.getCouponTypeId() && goodsTotalPrice.compareTo(couponVo.getMin_goods_amount()) >= 0) { // 可用优惠券
                couponVo.setEnabled(1);
                useCoupons.add(couponVo);
            } else {
                couponVo.setEnabled(0);
                notUseCoupons.add(couponVo);
            }
        }
        useCoupons.addAll(notUseCoupons);
        return toResponsSuccess(useCoupons);
    }



    /**
     * 兑换优惠券
     */
    @ApiOperation(value = "领券优惠券")
    @PostMapping("exchange")
    public Object exchange(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String coupon_number = jsonParam.getString("coupon_number");
        if (StringUtils.isNullOrEmpty(coupon_number)) {
            return toResponsFail("当前优惠码无效");
        }
        //
        Map param = new HashMap();
        param.put("coupon_number", coupon_number);
        List<UserCouponVo> couponVos = apiUserCouponService.queryList(param);
        UserCouponVo userCouponVo = null;
        if (null == couponVos || couponVos.size() == 0) {
            return toResponsFail("当前优惠码无效");
        }
        userCouponVo = couponVos.get(0);
        if (null != userCouponVo.getUser_id() && !userCouponVo.getUser_id().equals(0L)) {
            return toResponsFail("当前优惠码已经兑换");
        }
        CouponVo couponVo = apiCouponService.queryObject(userCouponVo.getCoupon_id());
        if (null == couponVo || null == couponVo.getCouponUseEndDate() || DateUtils.strToDate(couponVo.getCouponUseEndDate()).before(new Date())) {
            return toResponsFail("当前优惠码已经过期");
        }
        userCouponVo.setUser_id(loginUser.getUserId());
        userCouponVo.setAdd_time(new Date());
        apiUserCouponService.update(userCouponVo);
        return toResponsSuccess(userCouponVo);

    }

    /**
     * 　　领券优惠券
     *     新用户6折 满减 指定商品优惠券
     */
    @ApiOperation(value = "领取优惠券")
    @PostMapping("getCoupon")
    public Object getCoupon(@LoginUser UserVo loginUser) throws ParseException {
        JSONObject jsonParam = getJsonRequest();
        Integer couponId = jsonParam.getInteger("couponId");
        Integer userId=Integer.valueOf(loginUser.getUserId().intValue());

        //根据优惠券id查询优惠券的信息
        CouponVo coupon = apiCouponService.queryObject(couponId);

        // 是否领取过了
        Map params = new HashMap();
        params.put("user_id", userId);
        params.put("couponId", couponId);
        params.put("couponTypeId", coupon.getCouponTypeId());

        //暂时对小程序领取完后 后台工作人员再次发放没有限制
//        params.put("send_type", 4);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0 && 4!=coupon.getCouponTypeId()) {
            return toResponsFail("已经领取过，不能重复领取");
        }
        UserCouponVo userCouponVo = new UserCouponVo();
        try {
            // 领取
            //设置使用结束时间 couponTypeId=3 新用户首单六折 从用户领取时间开始算
            if (3==coupon.getCouponTypeId()){
                userCouponVo.setUse_end_date(plusDay(7));
            }else{
                //根据优惠券id查询该优惠券的使用结束时间
                userCouponVo.setUse_end_date(coupon.getCouponUseEndDate());
            }

            //指定天数
            if (coupon.getValidityType()!=null && 1==coupon.getValidityType()){
                userCouponVo.setUse_end_date(plusDay(coupon.getValidityDays()));
            }
            //指定日期
            if (coupon.getValidityType()!=null && 2==coupon.getValidityType()){
                userCouponVo.setUse_end_date(coupon.getUse_end_date());
            }
            userCouponVo.setAdd_time(new Date());
            userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
            userCouponVo.setUser_id(loginUser.getUserId());
            //此处设置优惠券id为1  也就是新用户首单六折
            userCouponVo.setCoupon_id(couponId);
            apiUserCouponService.save(userCouponVo);
        }catch (Exception e){
            e.printStackTrace();
            toResponsFail("领取失败");
        }
       return toResponsSuccess(userCouponVo);
    }


    /**
     * 　　转发领取红包
     */
    @ApiOperation(value = "转发领取红包")
    @PostMapping("transActivit")
    public Object transActivit(@LoginUser UserVo loginUser, String sourceKey, Long referrer) {
        JSONObject jsonParam = getJsonRequest();
        // 是否领取过了
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("send_type", 2);
        params.put("source_key", sourceKey);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return toResponsObject(2, "已经领取过", couponVos);
        }
        // 领取
        Map couponParam = new HashMap();
        couponParam.put("send_type", 1);
        CouponVo newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
        if (null != newCouponConfig) {
            UserCouponVo userCouponVo = new UserCouponVo();
            userCouponVo.setAdd_time(new Date());
            userCouponVo.setCoupon_id(newCouponConfig.getId());
            userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
            userCouponVo.setUser_id(loginUser.getUserId());
            userCouponVo.setSource_key(sourceKey);
            userCouponVo.setReferrer(referrer);
            apiUserCouponService.save(userCouponVo);

            //
            List<UserCouponVo> userCouponVos = new ArrayList();
            userCouponVos.add(userCouponVo);
            //
            params = new HashMap();
            params.put("user_id", loginUser.getUserId());
            params.put("send_type", 2);
            params.put("source_key", sourceKey);
            couponVos = apiCouponService.queryUserCoupons(params);
            return toResponsSuccess(couponVos);
        } else {
            return toResponsFail("领取失败");
        }
    }


    /**
     * 　　查询用户是否获取优惠券
     */
    @ApiOperation(value = "查询优惠券是否领取过")
    @PostMapping("queryCoupn")
    public Object queryCoupn(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        //
        String phone = jsonParam.getString("phone");
        Integer smscode = jsonParam.getInteger("smscode");
        Integer couponTypeId=jsonParam.getInteger("couponTypeId");
        Integer couponId=jsonParam.getInteger("couponId");
        // 校验短信码
        SmsLogVo smsLogVo = apiUserService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && smsLogVo.getSms_code() != smscode) {
            return toResponsFail("短信校验失败");
        }
        // 更新手机号码
        if (!StringUtils.isNullOrEmpty(phone)) {
            if (phone.equals(loginUser.getMobile())) {
                loginUser.setMobile(phone);
                apiUserService.update(loginUser);
            }
        }
        // 判断是否是新用户
//        if (!StringUtils.isNullOrEmpty(loginUser.getMobile())) {
//            //return toResponsFail("当前优惠券只能新用户领取");
//            return toResponsObject(201, "已经领取过，不能重复领取", "");
//        }

        // 是否领取过了
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("couponTypeId",couponTypeId);
        params.put("couponId",couponId);
//        params.put("send_type", 4);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0 && 4!=couponTypeId) {
            return toResponsObject(201, "已经领取过，不能重复领取", "");
        }

        //return toResponsMsgSuccess("没有领取过");
        return toResponsObject(200, "没有领取过", "");
    }

    /**
     * 指定商品优惠券单独发放
     */
    @IgnoreAuth
    @ApiOperation(value = "指定商品优惠券发放")
    @PostMapping("getGoodSendCoupon")
    public Object getGoodSendCoupon(@LoginUser UserVo loginUser){
        JSONObject jsonParam = getJsonRequest();
        String id = jsonParam.getString("id");
        Map params = new HashMap<>();
        params.put("user_id",loginUser.getUserId());
        params.put("send_type",3);
        params.put("id",id);
        List <CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (couponVos!= null && couponVos.size()>0){
            return toResponsFail("已经领取过,不能重复领取");
        }
        //领取
        Map couponParam = new HashMap();
        couponParam.put("send_type",3);
        params.put("id",id);
        CouponVo newCouponConfig = apiCouponService.queryObject(Integer.parseInt(id));
        //判断优惠券是否被领完
        Map userParams = new HashMap();
        userParams.put("coupon_id",id);
        int count = apiUserCouponService.queryUserGetTotal(userParams);
        if (newCouponConfig.getTotalCount()<= count){
            return toResponsFail("优惠券已领完");
        }
        if (newCouponConfig != null){
            UserCouponVo userCouponVo = new UserCouponVo();
            userCouponVo.setAdd_time(new Date());
            userCouponVo.setCoupon_id(newCouponConfig.getId());
            userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
            userCouponVo.setUser_id(loginUser.getUserId());
            userCouponVo.setMerchantId(newCouponConfig.getMerchantId());
            userCouponVo.setCoupon_price(newCouponConfig.getType_money());
            apiUserCouponService.save(userCouponVo);
            return toResponsSuccess(userCouponVo);
        }else {
            return toResponsFail("领取失败");
        }
    }

    private static String plusDay(int num) throws ParseException {
        Date oldDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdate = format.format(oldDate);
        System.out.println("现在的日期是：" + currdate);


        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
        oldDate = ca.getTime();
        String a = format.format(oldDate);
        System.out.println("a"+a);
        System.out.println("增加天数以后的日期：" + a);
        return a;
    }

}
